package com.duobeiyun.gmstest.work

import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.duobeiyun.generamessagesdk.ErrorInfo
import com.duobeiyun.generamessagesdk.ResultCallback
import com.duobeiyun.gmstest.TestInstance
import com.duobeiyun.gmstest.log.LogDebug
import com.duobeiyun.gmstest.log.LogOuter
import com.duobeiyun.gmstest.work.sample.WorkAsyncMode
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.suspendCancellableCoroutine
import java.nio.ByteBuffer
import kotlin.coroutines.resume

/**
 * 测试发送点对点消息
 */
class WorkSendChannelMessage(appContext: Context, workerParams: WorkerParameters) :
        WorkAsyncMode(appContext, workerParams) {

    override fun setNumber() {
        TAG = "WorkSendChannelMessage"
        number = "5"
    }

    override fun realWork(continuation: CancellableContinuation<Result>) {

        val msg = "et_channel_msg.text.trim().toString()"

        val createMessage = TestInstance.createInstance?.createMessage(msg)
        createMessage?.targetUserId = TestInstance.targetUserId

//        2.发送消息给不存在的用户
//        createMessage?.targetUserId = TestInstance.notExistPerson

//        3.加上离线选项，发送二进制消息给该用户
//        var byteA = msg.toByteArray()
//        var allocate = ByteBuffer.allocate(byteA.size)
//        allocate.put(byteA)
//        val createMessage = TestInstance.createInstance?.createMessage(allocate)

        TestInstance.sendMessage(createMessage, object : ResultCallback<Void> {
            override fun onSuccess(responseInfo: Void?) {
                LogOuter.print("number:$number \t result:${true} \t name:SendChannelMessage ")
                Log.e("MainActivity", "sendMessage success")

                continuation.resume(Result.success())
            }

            override fun onFailure(errorInfo: ErrorInfo) {
                LogDebug.logE(errorInfo.toString())
                LogOuter.print("number:$number \t result:${false} \t name:SendChannelMessage ")
                Log.e("MainActivity", "sendMessage failure:" + errorInfo.errorMsg)

                continuation.resume(Result.success())
            }
        })
    }


}